package com.mall.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mall.common.exception.BizException;
import com.mall.common.util.IdGenerator;
import com.mall.system.entity.UserEntity;
import com.mall.system.mapper.UserMapper;
import com.mall.system.service.UserService;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 用户服务实现类
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, UserEntity> implements UserService {

    @Override
    public UserEntity getByUsername(String username) {
        QueryWrapper<UserEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        return getOne(queryWrapper);
    }

    @Override
    public UserEntity getByMobile(String mobile) {
        QueryWrapper<UserEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("mobile", mobile);
        return getOne(queryWrapper);
    }

    @Override
    public UserEntity getByEmail(String email) {
        QueryWrapper<UserEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("email", email);
        return getOne(queryWrapper);
    }

    @Override
    public UserEntity getByThirdPartyId(String thirdPartyId) {
        QueryWrapper<UserEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("third_party_id", thirdPartyId);
        return getOne(queryWrapper);
    }

    @Override
    public UserEntity getById(Long userId) {
        QueryWrapper<UserEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        return getOne(queryWrapper);
    }

    @Override
    public boolean register(UserEntity user) {
        // 检查用户名是否已存在
        UserEntity existUser = getByUsername(user.getUsername());
        if (existUser != null) {
            throw new BizException("用户名已存在");
        }
        
        // 如果是第三方登录用户，检查第三方ID是否已存在
        if (user.getThirdPartyId() != null && !user.getThirdPartyId().isEmpty()) {
            UserEntity existThirdUser = getByThirdPartyId(user.getThirdPartyId());
            if (existThirdUser != null) {
                throw new BizException("第三方账号已绑定");
            }
        }
        
        // 密码加密
        if (user.getPassword() != null && !user.getPassword().isEmpty()) {
            String md5Password = DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
            user.setPassword(md5Password);
        }
        
        // 设置默认值
        user.setUserId(IdGenerator.nextId());
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        user.setStatus(1);
        
        return save(user);
    }
    
    @Override
    public UserEntity create(UserEntity user) {
        // 直接创建用户，不进行重复检查（由调用方保证）
        // 密码加密
        if (user.getPassword() != null && !user.getPassword().isEmpty()) {
            String md5Password = DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
            user.setPassword(md5Password);
        }
        
        // 设置默认值
        if (user.getUserId() == null) {
            user.setUserId(IdGenerator.nextId());
        }
        if (user.getCreateTime() == null) {
            user.setCreateTime(LocalDateTime.now());
        }
        user.setUpdateTime(LocalDateTime.now());
        if (user.getStatus() == null) {
            user.setStatus(1);
        }
        
        boolean success = save(user);
        if (success) {
            return user;
        } else {
            throw new BizException("创建用户失败");
        }
    }
}